<!--
@Description:潜在客户新增
@Author:zqy
@Date:2022-10-21 14:28:32
@Last Modified by:zqy
@Last Modified time:2022-10-21 14:28:32
-->
<template>
  <div class="page-has-bottom bg_gray">
    <ComHeader :title="pageTitle" bg-color="#FAFBFE" @get-height="handleHeadHeight" />
    <div class="cus-fixed-bottom">
      <van-button type="primary" block round class="cus-btn-submit" :disabled="!enbleSubmit" @click="handleSubmit">保存</van-button>
    </div>
    <van-form :show-error-message="false" @submit="handleSubmit">
      <div class="f-group">
        <div class="group-title">
          <span>基本信息</span>
        </div>
        <div class="custom-form">
          <Cell
            v-model="formData.name"
            title="姓名"
            placeholder="请填写姓名(必填),最多4个字符"
            required
            :rules="formRules.name"
            :right="false"
            is-input
            maxlength="4"
          />
          <Cell
            v-model="formData.phone"
            title="手机"
            :placeholder="`请填写手机${isIntentionalCustomer?'(必填)':''}`"
            type="tel"
            :required="isIntentionalCustomer"
            format-trigger="onBlur"
            :formatter="formatterTel"
            :right="false"
            is-input
          />
          <Cell
            v-if="!!clueCustomerId"
            :value="disCustomerSource"
            title="客户来源"
            required
            :right="false"
          />
          <FieldPicker
            v-else
            v-model="formData.disSecondSource"
            title="客户来源"
            placeholder="请选择(必选)"
            url="/data-dict/app/v2/dictionary/child"
            label-name="dictName"
            value-name="dictCode"
            method="post"
            required
            :params="{
              query:{
                appCode:'top2-crm',
                domainCode:'marketing',
                parentDictTypeCode:'DIS_CUSTOMER_PRIMARY_SOURCE',
                parentDictCode:'Offline',
              },
              type:2
            }"
          />

          <FieldPicker
            v-model="formData.shopDeptCode"
            :label.sync="formData.shopDeptName"
            title="所属门店部门"
            placeholder="请选择(必选)"
            :url="shopApi"
            label-name="orgName"
            value-name="orgCode"
            method="get"
            required
            :rules="[
              { required: true, message: '请选择(必选)' }
            ]"
            @change="handlerShopDeptChange"
          />
          <FieldArea
            v-model="customArea"
            title="所在地区"
            :option="areaOption"
            :required="false"
          />
          <Cell
            v-model="formData.detailedAddress"
            title="详细地址"
            placeholder="请输入详细地址"
            :right="false"
            is-input
          />
          <Cell
            v-model="formData.comments"
            title="备注"
            placeholder="请输入"
            :right="false"
            is-input
          />
          <Cell title="语音备注" custom :right="false">
            <FieldAudio
              v-model="formData.voiceRemark"
              :object-id="clueCustomerId || createId"
              module-type="ClueCustomerVoiceRemark"
              title="语音备注"
            />
          </Cell>
          <div v-show="showMore1">
            <FieldSelect
              v-model="formData.gender"
              title="性别"
              :url="`/data-dict/app/v2/dictionary/CRM_GENDER`"
              label-name="dictName"
              value-name="dictCode"
              method="get"
              :params="dictParams"
              clear
            />
            <FieldPicker
              v-model="formData.ageGroup"
              title="年龄段"
              placeholder="请选择"
              :url="`/data-dict/app/v2/dictionary/CRM_AGE_LEVEL`"
              label-name="dictName"
              value-name="dictCode"
              method="get"
              :params="dictParams"
              clear
            />
            <Cell
              v-model="formData.profession"
              title="职业"
              placeholder="请输入"
              :right="false"
              is-input
              input-align="right"
            />
            <FieldDateTime
              v-model="formData.birthday"
              title="生日"
              placeholder="请选择"
              type="date"
              :max-date="birthdayMaxDate"
              :min-date="birthdayMinDate"
              clear
            />
            <Cell
              v-model="formData.backupContact"
              title="第二联系方式"
              placeholder="请输入"
              :right="false"
              is-input
              input-align="right"
            />
            <Cell
              v-model="formData.wechatNumber"
              title="微信号"
              placeholder="请输入"
              :maxlength="50"
              :right="false"
              is-input
              input-align="right"
            />
          </div>
          <div class="btn-more" @click="showMore1=!showMore1">{{ showMore1?'收起':'展开' }}</div>
        </div>
      </div>
      <div class="f-group">
        <div class="group-title">
          <span>需求信息</span>
        </div>
        <div class="custom-form">
          <FieldSelect
            v-model="formData.categorySelection"
            :label.sync="formData.categorySelectionName"
            title="需求品类"
            placeholder="请选择"
            :url="`/data-dict/app/v2/dictionary/CRM_CATEGORY_SELECTION`"
            label-name="dictName"
            value-name="dictCode"
            method="get"
            :params="dictParams"
            multiple
            clear
            :includes="disConfCategorySelection"
          />
          <!-- :excludes="['FinishedProductFurniture']" -->

          <div v-show="showMore2">
            <FieldSelect
              v-model="formData.demandSpace"
              title="需求空间"
              placeholder="请选择"
              :url="`/data-dict/app/v2/dictionary/CRM_DEMAND_SPACE`"
              label-name="dictName"
              value-name="dictCode"
              method="get"
              :params="dictParams"
              multiple
              clear
            />
            <FieldPicker
              v-model="formData.customerBudget"
              title="客户预算"
              placeholder="请选择"
              :url="`/data-dict/app/v2/dictionary/CRM_CUSTOMER_BUDGET`"
              label-name="dictName"
              value-name="dictCode"
              method="get"
              :params="dictParams"
              clear
            />
            <FieldSelect
              v-model="formData.isEnterStore"
              title="是否进店"
              :option-data="[
                {label:'是',value:1},
                {label:'否',value:0}
              ]"
              value-name="value"
              label-name="label"
              clear
            />
            <Cell
              v-show="Number(formData.isEnterStore || 0) === 1"
              v-model="formData.enterStoreTimes"
              title="进店次数"
              placeholder="请输入"
              :maxlength="50"
              :right="false"
              type="digit"
              is-input
            />
          </div>
          <div class="btn-more" @click="showMore2=!showMore2">{{ showMore2?'收起':'展开' }}</div>
        </div>
      </div>
      <div class="f-group">
        <div class="group-title">
          <span>房屋信息</span>
        </div>
        <div class="custom-form">
          <Cell
            v-model="formData.housingEstate"
            title="小区"
            placeholder="请输入"
            :maxlength="50"
            :right="false"
            is-input
          />
          <FieldPicker
            v-model="formData.housingType"
            title="户型"
            placeholder="请选择"
            :url="`/data-dict/app/v2/dictionary/CRM_HOUSE_MODEL`"
            label-name="dictName"
            value-name="dictCode"
            method="get"
            :params="dictParams"
            clear
          />
          <FieldPicker
            v-model="formData.housingStyle"
            title="房屋类型"
            placeholder="请选择"
            :url="`/data-dict/app/v2/dictionary/CRM_HOUSE_TYPE`"
            label-name="dictName"
            value-name="dictCode"
            method="get"
            :params="dictParams"
            clear
          />
          <FieldSelect
            v-model="formData.isDeliveredHouse"
            title="是否交房"
            :option-data="[
              {label:'是',value:1},
              {label:'否',value:0}
            ]"
            value-name="value"
            label-name="label"
            clear
            @change="handlersIsDeliveredHouse"
          />
          <FieldDateTime
            v-if="[1, '1'].includes(formData.isDeliveredHouse)"
            v-model="formData.acceptanceTime"
            title="收房时间"
            placeholder="请选择"
            type="date"
            :default-date="formData.acceptanceTime"
            clear
            :required="[1, '1'].includes(formData.isDeliveredHouse)"
          />
          <FieldPicker
            v-model="formData.housingOverview"
            title="房屋状态"
            placeholder="请选择"
            :url="`/data-dict/app/v2/dictionary/CRM_HOUSE_SITUATION`"
            label-name="dictName"
            value-name="dictCode"
            method="get"
            :params="dictParams"
            clear
          />
          <FieldPicker
            v-model="formData.housingArea"
            title="房屋面积"
            placeholder="请选择"
            :url="`/data-dict/app/v2/dictionary/CRM_HOUSE_AREA`"
            label-name="dictName"
            value-name="dictCode"
            method="get"
            :params="dictParams"
            clear
          />
          <div v-show="isIntentionalCustomer">
            <FieldSelect
              v-model="optyCreateDTO.categorySelection"
              title="品类选择"
              placeholder="请选择"
              :url="`/data-dict/app/v2/dictionary/CRM_CATEGORY_SELECTION`"
              label-name="dictName"
              value-name="dictCode"
              method="get"
              :params="dictParams"
              clear
              multiple
              :required="!!isIntentionalCustomer"
            />
            <template v-if="!onlyContaineFinished">
              <!-- 品类只选择成品时，不显示设计师和量尺 -->
              <Cell
                title="申请设计师"
                :value="optyCreateDTO.recommendDesignerName"
                placeholder="请选择"
                :required="!!isIntentionalCustomer && !onlyContaineFinished"
                @right="handleClickDesigner"
              />
              <FieldDateTime
                v-model="optyCreateDTO.expectMeasuredTime"
                title="量尺时间"
                placeholder="请选择"
                type="datetime"
                :default-date="optyCreateDTO.expectMeasuredTime"
                :min-date="measuredMinDate"
                :required="!!isIntentionalCustomer && !onlyContaineFinished"
                clear
              />
            </template>
            <FieldPicker
              v-if="showMeal && !!(formData.disCode) "
              v-model="optyCreateDTO.setMealCode"
              :label.sync="optyCreateDTO.setMealName"
              title="套餐"
              placeholder="请选择"
              :url="`/app/v1/topSetMeal/${formData.disCode}/page`"
              label-name="productName"
              value-name="productCode"
              method="post"
              :params=" { query: {enabled:1,dr:0}, type: 0 }"
              clear
            />
          </div>
          <div v-show="showMore3">
            <FieldPicker
              v-model="formData.decorationBudget"
              title="装修预算"
              placeholder="请选择"
              :url="`/data-dict/app/v2/dictionary/CRM_Decoration_Budget`"
              label-name="dictName"
              value-name="dictCode"
              method="get"
              :params="dictParams"
              clear
            />
            <FieldPicker
              v-model="formData.decorationStage"
              title="装修阶段"
              placeholder="请选择"
              :url="`/data-dict/app/v2/dictionary/CRM_DECORATION_PHASE`"
              label-name="dictName"
              value-name="dictCode"
              method="get"
              :params="dictParams"
              clear
              @change="handlersDecorationStage"
            />
            <FieldPicker
              v-model="formData.constructionProgress"
              title="施工进度"
              placeholder="请选择"
              :url="`/data-dict/app/v2/dictionary/CRM_DECORATION_PROGRESS`"
              label-name="dictName"
              value-name="dictCode"
              method="get"
              :params="dictParams"
              clear
            />
            <FieldPicker
              v-model="formData.decorationStyle"
              title="装修风格"
              placeholder="请选择"
              :url="`/data-dict/app/v2/dictionary/CRM_Decoration_Style`"
              label-name="dictName"
              value-name="dictCode"
              method="get"
              :params="dictParams"
              clear
            />
            <FieldPicker
              v-model="formData.preferenceStyle"
              title="家居风格"
              placeholder="请选择"
              :url="`/data-dict/app/v2/dictionary/ADS_SPACE_PREFERENCE_STYLE`"
              label-name="dictName"
              value-name="dictCode"
              method="get"
              :params="dictParams"
              clear
            />
          </div>
          <div class="btn-more" @click="showMore3=!showMore3">{{ showMore3?'收起':'展开' }}</div>
        </div>
      </div>
    </van-form>
  </div>
</template>
<script>
import Cell from '@/components/ListCell'
import FieldArea from '@/components/FieldArea'
import FieldAudio from '@/components/FieldAudio'
import FieldSelect from '@/components/FieldSelect'
import FieldPicker from '@/components/FieldPicker'
import FieldDateTime from '@/components/FieldDateTime'
import { getId } from '@/apis/common'
import { getDictList } from '@/apis/dataDict'
import { getDisDetail, clueCustomerDisCreate, clueCustomerDisUpdate, distributorConfigCategoryByDisCode } from '@/apis/customer'
import { parseTime } from '@/utils'
import { bus } from '@/utils/bus'
const validatorPhone = (v) => {
  if (/^1[3456789]\d{9}$/.test(v) || v === '') {
    return true
  } else {
    return '手机号码格式有误'
  }
}
const validatorWechatNumber = (v) => {
  if (/^[\w]*$/.test(v)) {
    return true
  } else {
    return '微信号由数字和字母组成'
  }
}
const validatorNumber = (v) => {
  if (/^[\d]*$/.test(v) || v === '') {
    return true
  } else {
    return '只能包含数字'
  }
}
const validatorCSL = (v) => {
  if (!v || v.length === 0) {
    return ''
  } else {
    return true
  }
}
const validatorBackupContact = (v) => {
  if (v === '' || v === undefined || v === null) {
    return true
  }
  if (/^(1\d{10}|\d{3,4}-\d{7,8})$/.test(v)) {
    return true
  } else {
    return '手机号或座机号码格式有误'
  }
}
export default {
  name: 'CustomerAdd',
  components: {
    Cell, FieldArea, FieldAudio, FieldSelect, FieldPicker, FieldDateTime
  },
  data() {
    return {
      headHeight: 50,
      clueCustomerId: this.$route.query.id, // 线索客户ID(编辑时使用)
      customerType: Number(this.$route.query.type || 0) === 2 ? 2 : 1, // 客户类型：潜客：1，意向客户：2
      dictParams: { query: { appCode: 'top2-crm', domainCode: 'marketing' }, type: 0 },
      createId: '', // 创建新增时的ID（用户上传语音附件）
      formData: {
        name: '', // 顾客姓名
        phone: '', // 电话
        disSecondSource: '', // 顾客来源（三级来源）
        shopDeptCode: '', // 门店组织编码
        shopDeptName: '', // 门店组织名称
        shopName: '',
        shopCode: '',
        disCode: '',
        disName: '',

        provinceCode: '',
        provinceName: '',
        provinceId: '',
        cityCode: '',
        cityName: '',
        cityId: '',
        districtsCode: '',
        districtsName: '',
        districtsId: '',
        streetCode: '',
        streetName: '',
        streetId: '',
        detailedAddress: '',
        comments: '',
        voiceRemark: '', // 语音备注

        gender: '', // 性别
        ageGroup: '', // 年龄段
        profession: '', // 职业
        birthday: '', // parseTime(new Date(), '{y}-{m}-{d}'), // 生日
        backupContact: '', // 第二联系方式
        wechatNumber: '', // 微信号

        categorySelection: [], // 需求品类编码
        categorySelectionName: '', // 需求品类名称
        demandSpace: [], // 需求空间

        customerBudget: '', // 客户预算
        isEnterStore: '', // 是否进店
        enterStoreTimes: '', // 进店次数

        housingEstate: '', // 小区
        housingType: '', // 户型（CRM_HOUSE_MODEL）
        housingStyle: '', // 房屋类型(CRM_HOUSE_TYPE)
        isDeliveredHouse: '', // 是否已交房(1是，0 否)
        acceptanceTime: '', // 收房时间
        housingOverview: '', // 房屋概况(CRM_HOUSE_SITUATION)
        housingArea: '', // 面积(CRM_HOUSE_AREA)

        decorationBudget: '', // 装修预算(CRM_Decoration_Budget)
        decorationStage: '', // 装修阶段 (CRM_DECORATION_PHASE)
        constructionProgress: '', // 施工进度(CRM_DECORATION_PROGRESS)
        decorationStyle: '', // 装修风格(CRM_Decoration_Style)
        preferenceStyle: '' // 家居风格(ADS_SPACE_PREFERENCE_STYLE)
      },
      optyCreateDTO: {
        // 商机信息
        categorySelection: [], // 品类选择
        recommendDesignerEmployeeId: '', // 设计师ID
        recommendDesignerName: '', // 设计师名
        recommendDesignerUserAccount: '', // 设计师用户账号
        recommendDesignerUserId: '', // 设计师职用户ID
        expectMeasuredTime: parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'), // 量尺时间
        setMealCode: '', // 套餐编码
        setMealName: '' // 套餐名称
      }, // 商机信息
      customArea: {
        // 客户所在地区
        provinceId: '',
        provinceName: '',
        provinceCode: '',
        cityId: '',
        cityName: '',
        cityCode: '',
        districtsId: '',
        districtsName: '',
        districtsCode: '',
        streetId: '',
        streetName: '',
        streetCode: ''
      },
      areaOption: {
        provinceId: 'provinceId',
        province: 'provinceName',
        provinceCode: 'provinceCode',
        cityId: 'cityId',
        city: 'cityName',
        cityCode: 'cityCode',
        districtId: 'districtsId',
        district: 'districtsName',
        districtCode: 'districtsCode',
        townId: 'streetId',
        town: 'streetName',
        townCode: 'streetCode'
      },

      formRules: {
        name: [
          { required: true, message: '请输入客户姓名,不超过四个字' }
        ],
        disSecondSource: [{ required: true, message: '请选择客户来源' }],
        wechatNumber: [{ required: false, validator: validatorWechatNumber }],
        enterStoreTimes: [{ required: false, validator: validatorNumber }],
        shopDeptCode: [{ required: true, message: '请选择门店' }]
      },
      measuredMinDate: new Date(),
      showMore1: false,
      showMore2: false,
      showMore3: false,
      detail: {},
      birthdayMinDate: new Date(),
      birthdayMaxDate: new Date(),

      DIS_CUSTOMER_CLASSIFICATION: [],
      DIS_CUSTOMER_SECONDARY_SOURCE: [],
      disConfCategorySelection: []
    }
  },
  computed: {
    // 标题
    pageTitle() {
      let title = ''
      if (this.clueCustomerId) {
        title = '编辑'
      } else {
        title = `新增`
      }
      title = title + `${this.isIntentionalCustomer ? '意向' : '潜在'}客户`
      return title
    },
    // 是否意向客户
    isIntentionalCustomer() {
      return this.customerType === 2
    },
    // 是否店长
    isShopManager() {
      const t = this.$store.getters.userInfo
      return t.positionCodes && t.positionCodes.includes('top_shop_mg')
    },
    // 门店部门查询API(店长查直挂门店销售部门，非店长所属租户下销售部门)
    shopApi() {
      if (this.isShopManager) {
        return '/app/v1/organization/dis/queryMyDirectSaleDeptInTenant'
      }
      return '/app/v1/organization/dis/queryMySaleDeptInTenant'
    },
    // 是否包含定制
    containCustomize() {
      return this.optyCreateDTO.categorySelection instanceof Array && !this.optyCreateDTO.categorySelection.every(e => e === 'FinishedProductFurniture')
    },
    // 仅只包含成品
    onlyContaineFinished() {
      return this.optyCreateDTO.categorySelection instanceof Array && this.optyCreateDTO.categorySelection.length === 1 && this.optyCreateDTO.categorySelection[0] === 'FinishedProductFurniture'
    },
    // 是否显示套餐（品类选择成品且全屋定制时需选择套餐）
    showMeal() {
      const v = this.optyCreateDTO.categorySelection
      return v.includes('FinishedProductFurniture') && v.includes('WholeHouseCustom')
    },
    enbleSubmit() {
      let flag = true
      const requireds = ['name', 'disSecondSource', 'shopDeptCode']

      if (this.isIntentionalCustomer) {
        // 仅意向客户必选品类和手机号
        requireds.push('phone')
        // requireds.push('categorySelection')
      }
      for (const k of requireds) {
        const value = this.formData[k]
        if (value instanceof Array) {
          flag = value.length > 0
        } else {
          flag = ![null, undefined, ''].includes(value)
        }
        if (!flag) {
          break
        }
      }
      return flag
      // return this.checkDataRequired()
    },
    disCustomerSource() {
      const disCustomerClassification = this.DIS_CUSTOMER_CLASSIFICATION.find(e => e.dictCode === this.detail.disCustomerClassification)
      const disCustomerSecondSource = this.DIS_CUSTOMER_SECONDARY_SOURCE.find(e => e.dictCode === this.detail.disCustomerSecondSource)
      const names = []
      if (disCustomerClassification) {
        names.push(disCustomerClassification.dictName)
      }
      if (disCustomerSecondSource) {
        names.push(disCustomerSecondSource.dictName)
      } else {
        names.push(this.detail.disCustomerSecondSource || '')
      }

      return names.join('-')
    }
  },
  watch: {
    'formData.isEnterStore': {
      handler(v) {
        if (Number(v || 0) !== 1) {
          this.$set(this.formData, 'enterStoreTimes', '')
        }
      }
    },
    'formData.disCode': {
      handler(v) {
        this.getDisConfCategory(v)
      },
      immediate: true
    },
    showMeal(v) {
      if (!v) {
        this.$set(this.optyCreateDTO, 'setMealCode', '')
        this.$set(this.optyCreateDTO, 'setMealName', '')
      }
    },
    enbleSubmit() {
      return false
    }
  },
  created() {
    const date = new Date()
    const sDate = new Date().setFullYear(date.getFullYear() - 50)
    this.birthdayMinDate = new Date(sDate)

    if (this.clueCustomerId) {
      this.getDetail()
    } else {
      getId().then(res => {
        this.createId = res.data
      })
    }
    this.updateDesigner()
    if (this.isIntentionalCustomer) {
      // 意向客户品类和手机号必填
      this.$set(this.formRules, 'phone', [{ required: true, validator: validatorPhone }])
      // this.$set(this.formRules, 'categorySelection', [{ required: true, validator: validatorCSL, errMsg: '请选择需求品类' }])
    }
  },
  activated() {
    this.updateDesigner()
  },
  beforeRouteLeave(to, from, next) {
    // 判断要去的页面不是/customer/selectDesigner页，就删除keepAlive的缓存状态
    if (to.path !== '/customer/selectDesigner') {
      this.$removeKeepAliveCache(this)
    }
    next()
  },
  methods: {
    handleHeadHeight(h) {
      this.headHeight = h
    },
    getDetail() {
      this.getDataDict()
      getDisDetail(this.clueCustomerId).then(res => {
        const { birthday } = res.data
        if (birthday) {
          res.data.birthday = this.$parseTime(birthday, '{y}-{m}-{d}')
        }

        this.detail = res.data
        this.initFormData(this.detail, this.formData)
        this.initFormData(this.detail, this.optyCreateDTO)
        this.initFormData(this.detail, this.customArea)
        if (this.detail.voiceRemark && this.detail.voiceRemark.attachmentPath) {
          this.$set(this.formData, 'voiceRemark', this.$formatURL(this.detail.voiceRemark.attachmentPath))
        }
      })
    },
    initFormData(src, dst) {
      for (const [k, v] of Object.entries(dst)) {
        let value = src[k]
        if (k === 'disSecondSource') {
          value = src.disCustomerSecondSource
        }
        const isArry = v instanceof Array
        if (isArry && value) {
          value = value.split(',').filter(e => e !== '' && e !== undefined && e !== null)
        }
        const isObj = Object.prototype.toString.call(v) === '[object Object]'
        this.$set(dst, k, value !== undefined && value !== null ? value : isArry ? [] : isObj ? {} : '')
      }
    },
    getDataDict() {
      getDictList('DIS_CUSTOMER_CLASSIFICATION').then(res => {
        this.DIS_CUSTOMER_CLASSIFICATION = res
      })
      getDictList('DIS_CUSTOMER_SECONDARY_SOURCE').then(res => {
        this.DIS_CUSTOMER_SECONDARY_SOURCE = res
      })
    },
    updateDesigner() {
      const str = localStorage.getItem('custom-add-designer')
      if (str) {
        try {
          const obj = JSON.parse(str)
          this.setDesignerData(obj)
        } catch (error) {
          this.setDesignerData('')
        }
        localStorage.removeItem('custom-add-designer')
      } else {
        // this.setDesignerData('')
      }
    },
    formatterTel(value) {
      if (value && !(/^1[3456789]\d{9}$/.test(value))) {
        this.$toast('请填写正确的手机号')
      }
      return value
    },
    handlerShopDeptChange(v) {
      v = v || {}
      this.$set(this.formData, 'shopName', v.mdmOrgName || '')
      this.$set(this.formData, 'shopCode', v.mdmOrgCode || '')
      this.$set(this.formData, 'disCode', v.disCode || '')
      this.$set(this.formData, 'disName', v.disName || '')
      if (!v.shopDeptCode) {
        this.setDesignerData(null)
      }
    },
    // 选择设计师
    handleClickDesigner() {
      if (!this.formData.shopDeptCode) {
        this.$toast('请先选择门店')
        return
      }
      this.$router.push({ path: '/customer/selectDesigner', query: {
        orgCode: this.formData.shopDeptCode
      }})
    },
    // 设置设计师数据
    setDesignerData(v) {
      this.$set(this.optyCreateDTO, 'recommendDesignerUserAccount', v ? v.account : '')
      this.$set(this.optyCreateDTO, 'recommendDesignerName', v ? v.name : '')
      this.$set(this.optyCreateDTO, 'recommendDesignerEmployeeId', v ? v.id : '')
      this.$set(this.optyCreateDTO, 'recommendDesignerUserId', v ? v.userId : '')
    },
    handlersIsDeliveredHouse(v) {
      this.$set(this.formData, 'acceptanceTime', '')
      if (v && [1, '1'].includes(v.value) && this.formData.decorationStage === 'NotTransferHouse') {
        this.$set(this.formData, 'decorationStage', '')
      }
    },
    handlersDecorationStage(v) {
      if (v && [1, '1'].includes(this.formData.isDeliveredHouse) && v.dictCode === 'NotTransferHouse') {
        this.$set(this.formData, 'isDeliveredHouse', '0')
        this.$set(this.formData, 'acceptanceTime', '')
      }
    },
    checkDataRequired(isShow) {
      let flag = true
      for (const k in this.formData) {
        const val = this.formData[k]
        const isEmpty = val === '' || val.length === 0
        const reOb = this.formRules[k] ? this.formRules[k][0] : ''
        if (reOb) {
          if (reOb.required && isEmpty) {
            flag = false
            if (isShow) {
              this.$toast(reOb.message)
            }
            break
          }
          if (!isEmpty && reOb.validator && reOb.validator instanceof Function) {
            const msg = reOb.validator(val)
            if (msg !== true) {
              flag = false
              if (isShow) {
                this.$toast(msg || reOb.errMsg)
              }
              break
            }
          }
        }
      }

      /* if (!flag) {
        return flag
      }
      if (!this.customArea.districtsCode) {
        flag = false
        if (isShow) {
          this.$toast('请选择所在地区')
        }
      } */
      return flag
    },
    handleSubmit() {
      // const keyList = Object.keys(params)
      const flag = this.checkDataRequired(true)
      if (!flag) return
      if (this.formData.name.length > 4) {
        this.$toast('姓名不能大于4个字')
        return
      }
      const data = { ...this.formData, ...this.customArea }
      /* if (data.birthday) {
        data.birthday = `${data.birthday} 00:00:00`
      } */
      data.type = this.isIntentionalCustomer ? 2 : 1 // 客户类型：潜客 1，意向 2
      data.categorySelection = data.categorySelection ? data.categorySelection.join(',') : ''
      delete data.categorySelectionName
      data.demandSpace = data.demandSpace ? data.demandSpace.join(',') : ''

      if (this.isIntentionalCustomer) {
        // 意向客户获取商机信息
        const optyParams = {
          ...this.optyCreateDTO,
          ...{
            containCustomize: this.containCustomize,	// boolean 是否包含定制
            isShopOwnerCreate: this.isShopManager ? 1 : 0 //	integer($int32)是否店长创建:1=是，0=否
          }
        }

        if (optyParams.categorySelection && optyParams.categorySelection.length === 0) {
          this.$toast('请选择品类')
          return
        }
        optyParams.categorySelection = optyParams.categorySelection.join(',')
        if (!this.onlyContaineFinished) {
          if (!optyParams.recommendDesignerUserAccount) {
            this.$toast('请选择设计师')
            return
          }
          if (!optyParams.expectMeasuredTime) {
            this.$toast('请选择量尺时间')
            return
          }
        } else {
          this.setDesignerData()
        }
        data.optyCreateDTO = optyParams
      }
      if ([1, '1'].includes(this.formData.isDeliveredHouse) && !this.formData.acceptanceTime) {
        this.$toast('请选择收房时间')
        return
      }

      if (this.clueCustomerId) {
        data.id = this.clueCustomerId
      } else {
        data.id = this.createId
      }

      const saveFunc = this.clueCustomerId ? clueCustomerDisUpdate : clueCustomerDisCreate
      const headers = {
        'Permission-PerCode': 'my_customer_pool',
        'Permission-App': 'top2-crm-app'
      }
      saveFunc(data, headers).then(res => {
        if (res.success === 1) {
          this.$toast('保存成功')
          if (this.clueCustomerId) {
            bus.$emit('refreshCustomerItem', {
              title: '编辑',
              type: 'edit',
              id: this.clueCustomerId
            })
          } else {
            bus.$emit('refreshCustomerItem', {
              title: '新增',
              type: 'add'
            })
          }
          this.$router.go(-1)
        }
      }).catch((msg) => {
        this.$toast(msg || '保存失败')
      })
    },
    async getDisConfCategory(disCode) {
      this.disConfCategorySelection = []
      this.$set(this.formData, 'categorySelection', [])
      if (!disCode) {
        return
      }
      this.disConfCategorySelection = await distributorConfigCategoryByDisCode(disCode)
    }
  }
}
</script>
<style lang="less" scoped>
.group-title{
  padding: 16px 16px 6px;
  line-height: 18px;
  font-size: 12px;
  color: #888A9C;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.btn-more{
  color: #20CE92;
  font-size: 12px;
  text-align: center;
  padding: 10px 0;
  line-height: 1;
}
</style>
